<docs>
---
title: 国际化表
---

点击节点可复制国际化 key
</docs>

<template>
  <div>
    <el-tree
      :data="convertZhCn"
      :props="defaultProps"
      default-expand-all
      @node-click="handleNodeClick"
    />
  </div>
</template>

<script lang="ts" setup>
import { inject } from 'vue'
import { ElMessage } from 'element-plus'

const zhCn = inject('$zhCn')

const defaultProps = {
  children: 'children',
  label: 'label',
}

interface TreeNode {
  label: string
  children?: TreeNode[]
}

function convertData(data: Record<string, any>): TreeNode[] {
  const result: TreeNode[] = []
  delete data.name
  for (const key in data) {
    const item: TreeNode = { label: key }

    if (typeof data[key] === 'object') {
      item.children = convertData(data[key])
    } else {
      item.label = `${key}: ${data[key]}`
    }

    result.push(item)
  }
  // 交换 el 和 hsm 的位置
  if (result[0].label === 'el' && result[1].label === 'hsm') {
    const temp = result[0]
    result[0] = result[1]
    result[1] = temp
  }
  return result
}

const convertZhCn = convertData(zhCn as Record<string, any>)

// 点击节点时复制路径
const handleNodeClick = (data: any, node: any) => {
  if (data.children?.length) return
  const path: string[] = []
  getPath(node, path)
  const str = path.join('.')
  const key = str.split(':')[0]
  copyToClip(key)
  ElMessage.success(`复制成功: ${key}`)
}

function getPath(node: any, path: any) {
  if (node.parent) {
    getPath(node.parent, path)
  }
  if (node.data.label) {
    path.push(node.data.label)
  }
}

// 将内容放进剪切板
function copyToClip(str: string) {
  const ele = document.createElement('input')
  ele.style.height = '0'
  ele.setAttribute('value', str)
  document.body.appendChild(ele)
  ele.select()
  document.execCommand('copy')
  document.body.removeChild(ele)
}
</script>
